﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Evan.WebUI
{
    /// <summary>
    /// 管理后台的基类
    /// </summary>
    public class ManagerPage : System.Web.UI.Page
    {
        public BLL.Base Evan_BLL = new BLL.Base();
        /// <summary>
        /// token验证字符串
        /// </summary>
        public string Token = "";
        /// <summary>
        /// 系统提示
        /// </summary>
        public List<Evan.Model.SysModel.SystemNotice> SystemNotice = new List<Model.SysModel.SystemNotice>();
        /// <summary>
        /// 全局配置 此项不存在与数据库中 , 只可以在后台使用  
        /// </summary>
        public dynamic GlobalConfig = new Model.DynamicModel();
        /// <summary>
        /// 全局配置 此项不存在与数据库中 , 只可以在后台使用   , 作为 GlobalConfig 的替换品
        /// <para>目前此项和GlobalConfig兼容和同时使用 , 后期版本会慢慢去掉GlobalConfig . </para>
        /// </summary>
        public Evan.Model.SysModel.GlobalConfigModel GlobalConfigModel = new Model.SysModel.GlobalConfigModel();
        
        /// <summary>
        /// 获得当前页面(含目录)
        /// </summary>
        public string requestPath = HttpContext.Current.Request.Path.ToLower(); 
        //public DataBase.DbOperat DbOperat = new DataBase.DbOperat(); 
        /// <summary>
        /// 站点配置全局
        /// </summary>
        public dynamic SiteConfig = new Model.DynamicModel();
        List<dynamic> Lists_Temp = new Evan.DataBase.DbOperat("Channel").GetList(" States>-1 ", "SortId Asc,Id Asc");

        /// <summary>
        /// 系统配置 system.config
        /// </summary>
        public dynamic SystemConfig = new Model.DynamicModel();

        /// <summary>
        /// 加入待审核数量显示(胡法-深中使用)
        /// </summary>
        List<dynamic> Lists_art = new Evan.DataBase.DbOperat("Article").GetList(" States>-1 and IsVerify!=1", "SortId Asc,Id Asc");

        /// <summary>
        /// 当前栏目ClassId
        /// </summary>
        protected int ClassId = 0;


        /// <summary>
        /// 栏目菜单
        /// </summary>
        public StringBuilder ChannelMenu = new StringBuilder();
        /// <summary>
        /// 栏目列表
        /// </summary>
        protected List<dynamic> Channel_List = new List<dynamic>(); //栏目列表

        /// <summary>
        /// 当前栏目
        /// </summary>
        protected dynamic CurChannel = new Model.DynamicModel();
        /// <summary>
        /// 当前登录的管理员
        /// </summary>
        public dynamic CurAdmin = new Model.DynamicModel();

        /// <summary>
        /// 
        /// </summary>
        public ManagerPage()
        {
            Token = Common.CommFun.TokenGenerate(true);
            SiteConfig = Common.SysComm.GetSiteConfig();
            SystemConfig = Common.SysComm.GetSystemConfig();
            #region 增加参数 
            //string curDomain = HttpContext.Current.Request.Url.Host;
            //if (curDomain.ToLower() == "localhost".ToLower() || curDomain.EndsWith("kaola.ws",StringComparison.OrdinalIgnoreCase)) //本地调试 放行
            //{
            //    GlobalConfig.Set("Dev", 1);
            //}
            //else
            //{
            //    GlobalConfig.Set("Dev", 0);
            //}
            GlobalConfig.Set("Dev", 0);
            GlobalConfig.Set("IsShowIndex", 0);
            GlobalConfig.Set("IsModuleSystem", 0);
            if (!string.IsNullOrEmpty(Common.CommFun.GetQueryString("dev")))
            {
                if (Common.CommFun.GetQueryString("dev") == "1")
                {
                    GlobalConfigModel.Dev = true;
                    //随便写个cookie值，为了下面的逻辑
                    Common.CommFun.AddCookie("evan_dev", Guid.NewGuid().ToString(), 0, 2);
                }
            }

            //添加cookie验证开启开发者模式 为了小修改时方便，也不会忘记关闭开发者模式（导致客户误操作），
            if (!string.IsNullOrEmpty(Common.CommFun.GetCookie("evan_dev")))
            {
                GlobalConfigModel.Dev = true;
            }

            if (Common.CommFun.GetAppSetting("DevMode") == "1")
            {
                GlobalConfig.Set("Dev", 1);
                GlobalConfigModel.Dev = true;
            }

            if (Common.CommFun.GetAppSetting("IsShowIndex") == "1")
            {
                GlobalConfig.Set("IsShowIndex", 1);
                GlobalConfigModel.IsShowIndex = true;
            }

            if (Common.CommFun.GetAppSetting("IsModuleSystem") == "1")
            {
                GlobalConfig.Set("IsModuleSystem", 1);
                GlobalConfigModel.IsModuleSystem = true;
            }
            #endregion


            #region 项目中是否存在审核
            GlobalConfig.Set("HasVerify", Common.CommFun.GetAppSetting("HasVerify").ToInt32());
            if (Common.CommFun.GetAppSetting("HasVerify") == "1")
            {
                GlobalConfigModel.HasVerify = true;
            }
            #endregion



            this.Load += new EventHandler(ManagerPage_Load);
        }

        private void ManagerPage_Load(object sender, EventArgs e)
        {

            //#region 验证站点
            //HttpContext context = HttpContext.Current;
            ////在最前面 需要验证网站是否通过验证 过期10天内后台会有提示
            //Evan.Reg.VerifoNotice verifyRes = Evan.Reg.Security.CheckReg();
            //if (!verifyRes.Result)
            //{
            //    if (verifyRes.ExpiredDay > 7) //大于7
            //    {
            //        context.Response.StatusCode = 423;
            //        context.Response.TrySkipIisCustomErrors = true;
            //        context.Response.Write(Security.SefaTip.ReturnErrorMsg(verifyRes.Reason + verifyRes.ExpiredDay + "天 , 过期10天前台页面将出现此页面 , 无法正常浏览 , 请尽快联系您的客户经理"));
            //        context.Response.End();
            //    }
            //    if (verifyRes.ExpiredDay == -1)
            //    {
            //        context.Response.StatusCode = 423;
            //        context.Response.TrySkipIisCustomErrors = true;
            //        context.Response.Write(Security.SefaTip.ReturnErrorMsg(verifyRes.Reason + " , 请尽快联系您的客户经理"));   
            //        context.Response.End();
            //    }
            //}
            //#endregion

            //判断管理员是否登录
            if (!Member.Administrator.IsAdminLogin())
            {
                string return_url = SiteConfig.WebAdminPath + "login.aspx";
                string from = HttpContext.Current.Request.Url.AbsoluteUri;
                Response.Redirect(return_url + "?from=" + Common.CommFun.UrlEncode(from));
            }
            //判断管理员是否锁定
            if (Member.Administrator.IsAdminLock())
            {
                //锁定状态
                string return_url = SiteConfig.WebAdminPath + "lock.aspx";
                string from = HttpContext.Current.Request.Url.AbsoluteUri;
                Response.Redirect(return_url + "?from=" + Common.CommFun.UrlEncode(from));
            }
            else
            {
                //拿到当前管理员信息
                CurAdmin = Model.ConvertModel.ConvertToDynamic(Member.Administrator.GetAdminInfoFromCache());
                Calc_Channel(0);
                GetCurChannel();

                #region 检测密码强度给出提示
                if (!Evan.Common.RegexHelper.IsSafePwd(Evan.Member.Administrator.GetCurAdminPwd()))
                {
                    SystemNotice.Add(new Model.SysModel.SystemNotice { Type = "", Title = "您的密码过于简单 , 请立即修改密码", Level = 1, ActionType = "js", Action = "$('.layer-reset-pwd').click()" });
                }
                #endregion

                #region 检测网站授权给出提示
                //if (!verifyRes.Result)
                //{
                //    if (verifyRes.ExpiredDay <= 7) //小于7天和第七天
                //    {
                //        SystemNotice.Add(new Model.SysModel.SystemNotice { Type = "", Title = "网站授权已经过期" + verifyRes.ExpiredDay + "天 , 请立即处理", Level = 1, ActionType = "js", Action = "alert('过期7天后 , 后台将无法登陆<br/>过期10天后 , 整站将出现授权过期提示 , 无法正常访问<br/>为了不影响您网站的正常访问 , 请理解联系您的客户经理 .')" });
                //    }
                //}
                #endregion

                #region 检测密码修改间隔给出提示
                DateTime curAdminLastRePwdTime = Convert.ToDateTime(Member.Administrator.GetAdminInfoFromCache()["LastRePwdTime"].ToString());
                int AdminRePwd_Span = int.Parse(Config.WebConfig.GetAppSetting("RePwdTimeSpan", "60"));
                if (curAdminLastRePwdTime.AddDays(AdminRePwd_Span) < DateTime.Now)
                {
                    SystemNotice.Add(new Model.SysModel.SystemNotice { Type = "", Title = "距离上次修改密码已经过了" + AdminRePwd_Span + "天 , 为了保护您的密码安全 , 请立即修改密码", Level = 1, ActionType = "js", Action = "$('.layer-reset-pwd').click()" });
                }
                #endregion

            }
        }

        /// <summary>
        /// 是否含有快捷操作并且快捷操作是标记在列表显示的
        /// IsTop IsHot IsIndex IsRed
        /// </summary>
        /// <param name="classid"></param>
        /// <param name="opera"></param>
        /// <returns></returns>
        public bool IsHasQuickOpera(int classid, string opera)
        {
            List<dynamic> Field_List = new Evan.DataBase.DbOperat("Fields").GetList(string.Format("ClassId={0} and States=1 and IsList=1 and FieldName='{1}'", classid, opera));
            if (Field_List.Count > 0)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 验证权限
        /// </summary>
        /// <param name="HasRole"></param>
        public void VerifyRoles(bool HasRole = false)
        {
            if (!HasRole)
            {
                //如果没有权限  // 则回来做相应处理
                if (requestPath.EndsWith(".aspx"))
                {
                    HttpContext.Current.Response.Redirect(SiteConfig.WebAdminPath + "roles.aspx" + "?from=" + Common.CommFun.UrlEncode(HttpContext.Current.Request.Url.AbsoluteUri));
                }
                else if (requestPath.EndsWith(".ashx"))
                {
                    HttpContext.Current.Response.Write("{\"result\" :\"-100\",\"returnval\" :\"权限不足\"}");
                    HttpContext.Current.Response.End();
                }
            }
        }


        /// <summary>
        /// 获取当前栏目
        /// </summary>
        public void GetCurChannel()
        {
            int.TryParse(Common.CommFun.GetQueryString("classid"), out ClassId);
            if (ClassId > 0)
            {
                //获取当前栏目
                CurChannel = new Evan.DataBase.DbOperat("Channel").GetModel(ClassId);
            }
        }
        
        public void Calc_Channel(int PId)
        {
            List<dynamic> root = Lists_Temp.FindAll(res => res.ParentId == PId);
            foreach (var item in root)
            {
                item.Set("Deep", 0);
                Channel_List.Add(item);
                List<dynamic> root_1 = Lists_Temp.FindAll(res => res.ParentId == item.Id);
                foreach (var item_1 in root_1)
                {
                    item_1.Set("Deep", 1);
                    Channel_List.Add(item_1);
                    List<dynamic> root_2 = Lists_Temp.FindAll(res => res.ParentId == item_1.Id);
                    foreach (var item_2 in root_2)
                    {
                        item_2.Set("Deep", 2);
                        Channel_List.Add(item_2);
                        List<dynamic> root_3 = Lists_Temp.FindAll(res => res.ParentId == item_2.Id);
                        foreach (var item_3 in root_3)
                        {
                            item_3.Set("Deep", 3);
                            Channel_List.Add(item_3);
                            List<dynamic> root_4 = Lists_Temp.FindAll(res => res.ParentId == item_3.Id);
                            foreach (var item_4 in root_4)
                            {
                                item_4.Set("Deep", 4);
                                Channel_List.Add(item_4);
                                List<dynamic> root_5 = Lists_Temp.FindAll(res => res.ParentId == item_4.Id);
                                foreach (var item_5 in root_5)
                                {
                                    item_5.Set("Deep", 5);
                                    Channel_List.Add(item_5);
                                }
                            }
                        }
                    }
                }
            }
        }

        public string Deep(int deep)
        {
            string deep_str = "";
            for (int i = 0; i < deep; i++)
            {
                deep_str += "　";
            }
            return deep_str + "├";
        }

        public string SetNavToggle(string tagname, string managerpageurl)
        {
            string returnval = "";
            if (tagname == "a")
            {
                if (managerpageurl == "javascript:;")
                {
                    returnval = "nav-toggle";
                }
            }
            if (tagname == "span")
            {
                if (managerpageurl != "javascript:;")
                {
                    returnval = "nav-toggle";
                }
            }
            return returnval;
        }

        public string GetManagePageUrl(string url, int classid)
        {
            //if (url.StartsWith("List.aspx") || url.StartsWith("SinglePage.aspx"))
            //{
            //    return SiteConfig.WebAdminPath + "Page/" + url + "&classid=" + classid;
            //}
            //else
            //{
            //    return "javascript:;";
            //}
            if (string.IsNullOrEmpty(url) || url.ToLower().Contains("javascript") )
            {
                return "javascript:;";
            }
            else if (url.ToLower().StartsWith("page"))
            {
                return url;
            }
            else
            {
                return SiteConfig.WebAdminPath + "Page/" + url + "&classid=" + classid;
            }


        }


        /// <summary>
        /// 获取当前栏目下待审核的数量
        /// </summary>
        /// <param name="classid"></param>
        /// <returns></returns>
        public string GetIsLockNum(int classid)
        {
            int num = 0;
            List<dynamic> art1 = Lists_art.FindAll(res => res.ClassId == classid && res.States == 1);//读一级
            num += art1.Count;
            List<dynamic> root = Lists_Temp.FindAll(res => res.ParentId == classid && res.States == 1);
            if (root.Count > 0)
            {
                foreach (var item in root)
                {
                    List<dynamic> art2 = Lists_art.FindAll(res => res.ClassId == item.Id && res.States == 1);//读二级
                    num += art2.Count;
                    List<dynamic> root2 = Lists_Temp.FindAll(res => res.ParentId == item.Id && res.States == 1);
                    if (root2.Count > 0)
                    {
                        foreach (var item2 in root2)
                        {
                            List<dynamic> art3 = Lists_art.FindAll(res => res.ClassId == item2.Id && res.States == 1);//读三级
                            num += art3.Count;
                            List<dynamic> root3 = Lists_Temp.FindAll(res => res.ParentId == item2.Id && res.States == 1);
                            if (root3.Count > 0)
                            {
                                foreach (var item4 in root3)
                                {
                                    List<dynamic> art4 = Lists_art.FindAll(res => res.ClassId == item4.Id && res.States == 1);//读四级
                                    num += art4.Count;
                                }
                            }
                        }
                    }
                }
            }
            return "（" + num + "）";
        }

        /// <summary>
        /// 根据classid获取当前栏目是否可以显示 (有无权限 , 查看的权限)
        /// 返回两个类 hide norole 
        /// hide 隐藏类
        /// norole 标记类 用于前端删除
        /// </summary>
        /// <param name="thisClassId">栏目ID</param>
        /// <returns></returns>
        public string GetHasRoleByClassId(int thisClassId)
        {
            bool IsHasRole = Member.Administrator.HasRole(1, thisClassId.ToString(), "", "view");
            if (IsHasRole)
            {
                return "";
            }
            else {
                return " hide norole ";
            }
        }

        /// <summary>
        /// 根据系统页面名称获取当前是否有权限 , 用于系统页面
        /// 返回两个类 hide norole 
        /// hide 隐藏类
        /// norole 标记类 用于前端删除
        /// </summary>
        /// <param name="pageName">页面名称</param>
        /// <returns></returns>
        public string GetHasRoleByRoleName(string pageName)
        {
            bool IsHasRole = Member.Administrator.HasRole(0, "0", pageName, "");
            if (IsHasRole)
            {
                return "";
            }
            else
            {
                return " hide norole ";
            }
        }

        /// <summary>
        /// 组合栏目列表
        /// </summary>
        /// <param name="PId"></param>
        /// <returns></returns>
        public string MarkChannelMenu(int PId)
        {

            List<dynamic> root = Lists_Temp.FindAll(res => res.ParentId == PId && res.States == 1);
            foreach (var item in root)
            {
                //一级菜单开始
                List<dynamic> root_1 = Lists_Temp.FindAll(res => res.ParentId == item.Id && res.States == 1);
                ChannelMenu.Append("<li class=\"nav-item " + GetHasRoleByClassId(Convert.ToInt32(item.Id)) + " \" data-classid=\"" + item.Id + "\">");
                ChannelMenu.Append("    <a href=\"" + GetManagePageUrl(item.ManagePageUrl, item.Id) + "\" class=\"nav-link " + SetNavToggle("a", GetManagePageUrl(item.ManagePageUrl, item.Id)) + "\">");
                ChannelMenu.Append("    <span class=\"title\">" + item.Title + (GlobalConfig.HasVerify == 1 ? GetIsLockNum(item.Id) : "") + "</span>");
                if (root_1.Count > 0)
                {
                    ChannelMenu.Append("    <span class=\"arrow " + SetNavToggle("span", GetManagePageUrl(item.ManagePageUrl, item.Id)) + "\"></span>");
                }
                ChannelMenu.Append("    </a>");
                if (root_1.Count > 0)
                {
                    ChannelMenu.Append("<ul class=\"sub-menu\" style=\"display: none;\">");
                }
                foreach (var item_1 in root_1)
                {
                    //二级菜单开始
                    List<dynamic> root_2 = Lists_Temp.FindAll(res => res.ParentId == item_1.Id && res.States == 1);
                    ChannelMenu.Append("<li class=\"nav-item " + GetHasRoleByClassId(Convert.ToInt32(item_1.Id)) + " \" data-classid=\"" + item_1.Id + "\">");
                    ChannelMenu.Append("    <a href=\"" + GetManagePageUrl(item_1.ManagePageUrl, item_1.Id) + "\" class=\"nav-link " + SetNavToggle("a", GetManagePageUrl(item_1.ManagePageUrl, item_1.Id)) + "\">");
                    ChannelMenu.Append("    <span class=\"title\">" + item_1.Title + (GlobalConfig.HasVerify == 1 ? GetIsLockNum(item_1.Id) : "") + "</span>");
                    if (root_2.Count > 0)
                    {
                        ChannelMenu.Append("    <span class=\"arrow " + SetNavToggle("span", GetManagePageUrl(item_1.ManagePageUrl, item_1.Id)) + "\"></span>");
                    }
                    ChannelMenu.Append("    </a>");
                    if (root_2.Count > 0)
                    {
                        ChannelMenu.Append("<ul class=\"sub-menu\" style=\"display: none;\">");
                    }
                    foreach (var item_2 in root_2)
                    {
                        //三级菜单开始
                        List<dynamic> root_3 = Lists_Temp.FindAll(res => res.ParentId == item_2.Id && res.States == 1);
                        ChannelMenu.Append("<li class=\"nav-item " + GetHasRoleByClassId(Convert.ToInt32(item_2.Id)) + " \" data-classid=\"" + item_2.Id + "\">");
                        ChannelMenu.Append("    <a href=\"" + GetManagePageUrl(item_2.ManagePageUrl, item_2.Id) + "\" class=\"nav-link " + SetNavToggle("a", GetManagePageUrl(item_2.ManagePageUrl, item_2.Id)) + "\">");
                        ChannelMenu.Append("    <span class=\"title\">" + item_2.Title + (GlobalConfig.HasVerify == 1 ? GetIsLockNum(item_2.Id) : "") + "</span>");
                        if (root_3.Count > 0)
                        {
                            ChannelMenu.Append("    <span class=\"arrow " + SetNavToggle("span", GetManagePageUrl(item_2.ManagePageUrl, item_2.Id)) + "\"></span>");
                        }
                        ChannelMenu.Append("    </a>");
                        if (root_3.Count > 0)
                        {
                            ChannelMenu.Append("<ul class=\"sub-menu\" style=\"display: none;\">");
                        }
                        foreach (var item_3 in root_3)
                        {
                            //四级菜单开始
                            List<dynamic> root_4 = Lists_Temp.FindAll(res => res.ParentId == item_3.Id && res.States == 1);
                            ChannelMenu.Append("<li class=\"nav-item " + GetHasRoleByClassId(Convert.ToInt32(item_3.Id)) + " \" data-classid=\"" + item_3.Id + "\">");
                            ChannelMenu.Append("    <a href=\"" + GetManagePageUrl(item_3.ManagePageUrl, item_3.Id) + "\" class=\"nav-link " + SetNavToggle("a", GetManagePageUrl(item_3.ManagePageUrl, item_3.Id)) + "\">");
                            ChannelMenu.Append("    <span class=\"title\">" + item_3.Title + (GlobalConfig.HasVerify == 1 ? GetIsLockNum(item_3.Id) : "") + "</span>");
                            if (root_4.Count > 0)
                            {
                                ChannelMenu.Append("    <span class=\"arrow " + SetNavToggle("span", GetManagePageUrl(item_3.ManagePageUrl, item_3.Id)) + "\"></span>");
                            }
                            ChannelMenu.Append("    </a>");
                            if (root_4.Count > 0)
                            {
                                ChannelMenu.Append("<ul class=\"sub-menu\" style=\"display: none;\">");
                            }
                            foreach (var item_4 in root_4)
                            {
                                //五级菜单开始
                                List<dynamic> root_5 = Lists_Temp.FindAll(res => res.ParentId == item_4.Id && res.States == 1);
                                ChannelMenu.Append("<li class=\"nav-item " + GetHasRoleByClassId(Convert.ToInt32(item_4.Id)) + " \" data-classid=\"" + item_4.Id + "\">");
                                ChannelMenu.Append("    <a href=\"" + GetManagePageUrl(item_4.ManagePageUrl, item_4.Id) + "\" class=\"nav-link " + SetNavToggle("a", GetManagePageUrl(item_4.ManagePageUrl, item_4.Id)) + "\">");
                                ChannelMenu.Append("    <span class=\"title\">" + item_4.Title + (GlobalConfig.HasVerify == 1 ? GetIsLockNum(item_4.Id) : "") + "</span>");
                                if (root_5.Count > 0)
                                {
                                    ChannelMenu.Append("    <span class=\"arrow " + SetNavToggle("span", GetManagePageUrl(item_4.ManagePageUrl, item_4.Id)) + "\"></span>");
                                }
                                ChannelMenu.Append("    </a>");
                                if (root_5.Count > 0)
                                {
                                    ChannelMenu.Append("<ul class=\"sub-menu\" style=\"display: none;\">");
                                }
                                foreach (var item_5 in root_5)
                                {
                                    //六级菜单开始
                                    ChannelMenu.Append("<li class=\"nav-item " + GetHasRoleByClassId(Convert.ToInt32(item_5.Id)) + " \" data-classid=\"" + item_5.Id + "\">");
                                    ChannelMenu.Append("    <a href=\"" + GetManagePageUrl(item_5.ManagePageUrl, item_5.Id) + "\" class=\"nav-link " + SetNavToggle("a", GetManagePageUrl(item_5.ManagePageUrl, item_5.Id)) + "\">");
                                    ChannelMenu.Append("    <span class=\"title\">" + item_5.Title + "</span>");
                                    ChannelMenu.Append("    </a>");
                                    ChannelMenu.Append("</li>");
                                    //六级菜单结束
                                }
                                //五级菜单结束
                                if (root_5.Count > 0)
                                {
                                    ChannelMenu.Append("</ul>");
                                }
                                ChannelMenu.Append("</li>");
                            }
                            //四级菜单结束
                            if (root_4.Count > 0)
                            {
                                ChannelMenu.Append("</ul>");
                            }
                            ChannelMenu.Append("</li>");
                        }
                        //三级菜单结束
                        if (root_3.Count > 0)
                        {
                            ChannelMenu.Append("</ul>");
                        }
                        ChannelMenu.Append("</li>");
                    }
                    //二级菜单结束
                    if (root_2.Count > 0)
                    {
                        ChannelMenu.Append("</ul>");
                    }
                    ChannelMenu.Append("</li>");
                }

                //一级菜单结束
                if (root_1.Count > 0)
                {
                    ChannelMenu.Append("</ul>");
                }
                ChannelMenu.Append("</li>");
            }

            return ChannelMenu.ToString();

        } 
    }
}
